package com.javaxiaobear.module.system.mapper;

import static com.javaxiaobear.module.system.domain.table.SysUserRoleTableDef.SYS_USER_ROLE;

import com.javaxiaobear.module.system.domain.SysUserRole;
import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.query.QueryWrapper;
import java.util.Arrays;
import java.util.List;
import org.apache.ibatis.annotations.Param;

/**
 * 用户与角色关联表 数据层
 *
 * @author javaxiaobear
 */
public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {
  /** 通过用户ID删除用户和角色关联 */
  default int deleteUserRoleByUserId(Long userId) {
    QueryWrapper queryWrapper = QueryWrapper.create().where(SYS_USER_ROLE.USER_ID.eq(userId));
    return deleteByQuery(queryWrapper);
  }

  /** 批量删除用户和角色关联 */
  default int deleteUserRole(Long[] ids) {
    if (ids == null || ids.length == 0) {
      return 0;
    }
    QueryWrapper queryWrapper =
        QueryWrapper.create().where(SYS_USER_ROLE.USER_ID.in(Arrays.asList(ids)));
    return deleteByQuery(queryWrapper);
  }

  /** 通过角色ID查询角色使用数量 */
  default int countUserRoleByRoleId(Long roleId) {
    QueryWrapper queryWrapper = QueryWrapper.create().where(SYS_USER_ROLE.ROLE_ID.eq(roleId));
    return Math.toIntExact(selectCountByQuery(queryWrapper));
  }

  /** 批量新增用户角色信息 */
  default int batchUserRole(List<SysUserRole> userRoleList) {
    if (userRoleList == null || userRoleList.isEmpty()) {
      return 0;
    }
    return insertBatch(userRoleList);
  }

  /** 删除用户和角色关联信息 */
  default int deleteUserRoleInfo(SysUserRole userRole) {
    QueryWrapper queryWrapper =
        QueryWrapper.create()
            .where(SYS_USER_ROLE.USER_ID.eq(userRole.getUserId()))
            .and(SYS_USER_ROLE.ROLE_ID.eq(userRole.getRoleId()));
    return deleteByQuery(queryWrapper);
  }

  /** 批量取消授权用户角色 */
  default int deleteUserRoleInfos(@Param("roleId") Long roleId, @Param("userIds") Long[] userIds) {
    if (roleId == null || userIds == null || userIds.length == 0) {
      return 0;
    }
    QueryWrapper queryWrapper =
        QueryWrapper.create()
            .where(SYS_USER_ROLE.ROLE_ID.eq(roleId))
            .and(SYS_USER_ROLE.USER_ID.in(Arrays.asList(userIds)));
    return deleteByQuery(queryWrapper);
  }
}
